<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="include :: header('添加实验项目')" />
    <th:block th:include="include :: datetimepicker-css" />
    <style>
        /* 日期选择器输入框对齐优化 */
        .input-group.date {
            width: 100%;
        }
        /* 文件上传按钮美化 */
        .file-input-wrapper .form-control {
            background-color: #f8f9fa;
            cursor: default;
        }
        /* 富文本编辑器加载提示样式 */
        #editorLoading, #purposeLoading {
            border: 1px dashed #ced4da;
            border-radius: 4px;
            margin-top: 5px;
            padding: 15px 0;
        }
        /* 表单提示文字间距优化 */
        .text-info.m-t-10 {
            margin-top: 8px !important;
            font-size: 13px;
        }
        /* 提交按钮加载状态 */
        .btn-loading {
            background-color: #6c757d !important;
            border-color: #6c757d !important;
            cursor: not-allowed;
        }
        /* 基础代码块样式 */
        pre.code-block {
            background-color: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 4px;
            padding: 10px;
            overflow-x: auto;
            margin: 10px 0;
        }
        pre.code-block code {
            color: #333;
            font-family: "Courier New", Courier, monospace;
            font-size: 13px;
        }
    </style>
</head>
<body class="gray-bg">
<div class="wrapper wrapper-content">
    <div class="row">
        <div class="col-sm-12">
            <div class="ibox float-e-margins">
                <div class="ibox-title">
                    <h5>实验项目信息</h5>
                    <div class="ibox-tools">
                        <a class="collapse-link"><i class="fa fa-chevron-up"></i></a>
                    </div>
                </div>
                <div class="ibox-content">
                    <form class="form-horizontal m-t" id="addForm" enctype="multipart/form-data" method="post">
                        <input type="hidden" name="arrangementId" th:value="${arrangementId}" />

                        <!-- 实验项目名称 -->
                        <div class="form-group">
                            <label class="col-sm-3 control-label">实验项目名称：<span class="text-danger">*</span></label>
                            <div class="col-sm-8">
                                <input type="text" name="projectName" class="form-control"
                                       placeholder="请输入实验项目名称（如：Linux软件安装）" required>
                            </div>
                        </div>

                        <!-- 新增：实验学时 -->
                        <div class="form-group">
                            <label class="col-sm-3 control-label">实验学时：<span class="text-danger">*</span></label>
                            <div class="col-sm-8">
                                <input type="number" name="experimentPeriod" class="form-control"
                                       placeholder="请输入实验学时（如：2、4、6）" min="1" required>
                            </div>
                            <div class="col-sm-12 text-info text-center m-t-10">
                                提示：填写实验所需的标准学时数，单位为学时（通常为1-8学时）
                            </div>
                        </div>

                        <!-- 实验序号 -->
                        <div class="form-group">
                            <label class="col-sm-3 control-label">实验序号：<span class="text-danger">*</span></label>
                            <div class="col-sm-8">
                                <input type="text" name="experimentNumber" class="form-control"
                                       placeholder="如：1、2、3（按实验顺序填写）" required>
                            </div>
                        </div>

                        <!-- 学期开始日期（修复回显问题） -->
                        <div class="form-group">
                            <label class="col-sm-3 control-label">实验时间：</label>
                            <div class="col-sm-8">
                                <div class="input-group date" id="startDatePicker">
                                    <input name="experimentTime" class="form-control" placeholder="yyyy-MM-dd HH:mm:ss" type="text" readonly>
                                    <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                                </div>
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="col-sm-3 control-label">截止时间：</label>
                            <div class="col-sm-8">
                                <div class="input-group date" id="endDatePicker">
                                    <input name="deadline" class="form-control" placeholder="yyyy-MM-dd HH:mm:ss" type="text" readonly>
                                    <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                                </div>
                            </div>
                        </div>

                        <!-- 相关资料上传 -->
                        <div class="form-group">
                            <label class="col-sm-3 control-label">相关资料上传：</label>
                            <div class="col-sm-8 file-input-wrapper">
                                <div class="input-group">
                                    <input type="text" class="form-control" id="fileShowName" readonly
                                           placeholder="未选择任何文件">
                                    <span class="input-group-btn">
                                        <label class="btn btn-default" for="files">选择文件</label>
                                    </span>
                                    <input type="file" id="files" name="files" class="hidden"
                                           multiple accept=".pdf,.doc,.docx,.ppt,.pptx,.zip,.rar">
                                </div>
                                <div class="text-muted m-t-3">支持格式：pdf、doc、docx、ppt、pptx、zip（可多选，单个文件不超过50MB）</div>
                            </div>
                        </div>

                        <!-- 实验目的 -->
                        <div class="form-group">
                            <label class="col-sm-3 control-label">实验目的：</label>
                            <div class="col-sm-8">
                                <textarea name="purpose" class="form-control" rows="2"
                                          placeholder="可选：填写实验注意事项、特殊要求等"></textarea>
                            </div>
                        </div>

                        <!-- 实验内容 -->
                        <div class="form-group">
                            <label class="col-sm-3 control-label">实验内容：<span class="text-danger">*</span></label>
                            <div class="col-sm-8">
                                <textarea name="content" id="content" class="form-control hidden" rows="5" required></textarea>
                                <div id="editorLoading" class="text-muted text-center py-3">
                                    富文本编辑器加载中...（支持插入图片、表格、视频、代码块）
                                </div>
                            </div>
                            <div class="col-sm-12 text-info text-center m-t-10">
                                提示：1. 图片/文件需先上传至服务器再插入；2. 代码可通过「源码」按钮插入&lt;pre class="code-block"&gt;&lt;code&gt;代码&lt;/code&gt;&lt;/pre&gt;；3. 复杂步骤建议分段编辑
                            </div>
                        </div>

                        <!-- 备注 -->
                        <div class="form-group">
                            <label class="col-sm-3 control-label">备注：</label>
                            <div class="col-sm-8">
                                <textarea name="remark" class="form-control" rows="2"
                                          placeholder="可选：填写实验注意事项、特殊要求等"></textarea>
                            </div>
                        </div>

                        <!-- 提交/取消按钮 -->
                        <div class="form-group">
                            <div class="col-sm-12 text-center">
                                <button class="btn btn-primary" type="submit" id="submitBtn">提交</button>
                                <button class="btn btn-white m-l-20" type="button" onclick="history.back()">取消</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 引入公共JS -->
<th:block th:include="include :: footer" />
<th:block th:include="include :: datetimepicker-js" />
<script th:src="@{/plugins/ckeditor/ckeditor.js}"></script>

<script th:inline="javascript">
    $(function() {
        // 1. 日期时间选择器初始化（修复回显问题）
        // 关键修复：将分钟占位符从ii改为标准的mm
        // 修改日期时间选择器的初始化代码
        function initDateTimePicker() {
            // 修改日期时间选择器的 changeDate 事件处理
            $('#startDatePicker').datetimepicker({
                format: "yyyy-mm-dd HH:mm:ss",
                language: "zh-CN",
                minView: 0,
                viewSelect: "second",
                showSeconds: true,
                todayBtn: true,
                todayHighlight: true,
                clearBtn: true,
                autoclose: true,
                pickerPosition: "bottom-left",
                forceParse: true,
                defaultDate: $('input[name="experimentTime"]').val() || new Date()
            }).on('changeDate', function(e) {
                // 修复：使用事件对象中的日期并手动格式化
                if (e.date) {
                    const year = e.date.getFullYear();
                    const month = String(e.date.getMonth() + 1).padStart(2, '0');
                    const day = String(e.date.getDate()).padStart(2, '0');
                    const hours = String(e.date.getHours()).padStart(2, '0');
                    const minutes = String(e.date.getMinutes()).padStart(2, '0');
                    const seconds = String(e.date.getSeconds()).padStart(2, '0');

                    const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
                    $('input[name="experimentTime"]').val(formattedDate);
                }
            });

            // 修改日期时间选择器的 changeDate 事件处理
            $('#endDatePicker').datetimepicker({
                format: "yyyy-mm-dd HH:mm:ss",
                language: "zh-CN",
                minView: 0,
                viewSelect: "second",
                showSeconds: true,
                todayBtn: true,
                todayHighlight: true,
                clearBtn: true,
                autoclose: true,
                pickerPosition: "bottom-left",
                forceParse: true,
                defaultDate: $('input[name="deadline"]').val() || new Date()
            }).on('changeDate', function(e) {
                // 修复：使用事件对象中的日期并手动格式化
                if (e.date) {
                    const year = e.date.getFullYear();
                    const month = String(e.date.getMonth() + 1).padStart(2, '0');
                    const day = String(e.date.getDate()).padStart(2, '0');
                    const hours = String(e.date.getHours()).padStart(2, '0');
                    const minutes = String(e.date.getMinutes()).padStart(2, '0');
                    const seconds = String(e.date.getSeconds()).padStart(2, '0');

                    const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
                    $('input[name="deadline"]').val(formattedDate);
                }
            });
        }
        initDateTimePicker();

        // 2. 文件上传组件
        $('#files').on('change', function() {
            const files = this.files;
            if (files.length === 0) {
                $('#fileShowName').val('未选择任何文件');
                return;
            }
            const fileNames = Array.from(files).map(file => file.name);
            const showText = fileNames.length > 3
                ? `${fileNames.slice(0,3).join('、')} 等${fileNames.length}个文件`
                : fileNames.join('、');
            $('#fileShowName').val(showText);
        });

        // 3. 富文本编辑器初始化
        const contentEditor = CKEDITOR.replace('content', {
            height: 180,
            toolbar: [
                ['Bold', 'Italic', 'Underline', 'Strike'],
                ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent'],
                ['Link', 'Unlink'],
                ['Image', 'Table'],
                ['Source', 'Maximize']
            ],
            allowedContent: true,
            filebrowserUploadUrl: ctx + "common/upload/file",
            filebrowserImageUploadUrl: ctx + "common/upload/image",
            on: {
                instanceReady: function() {
                    $('#editorLoading').hide();
                    this.on('change', function() {
                        const content = this.getData().replace(/&nbsp;|\s|<[^>]+>/g, '');
                        $('textarea[name="content"]').prop('required', content.length === 0);
                    });
                }
            }
        });

        // 4. 表单验证（修复验证规则）
        $("#addForm").validate({
            rules: {
                projectName: { required: true, maxlength: 50 },
                experimentNumber: { required: true, digits: true, min: 1 },
                experimentPeriod: { required: true, digits: true, min: 1 }, // 新增：实验学时验证
                content: { required: true }
            },
            messages: {
                projectName: {
                    required: "请输入实验项目名称",
                    maxlength: "名称长度不能超过50个字符"
                },
                experimentNumber: {
                    required: "请输入实验序号",
                    digits: "序号必须为数字",
                    min: "序号不能小于1"
                },
                content: { required: "请填写实验内容" }
            },
            submitHandler: function(form) {
                contentEditor.updateElement();
                const content = $('textarea[name="content"]').val().replace(/&nbsp;|\s|<[^>]+>/g, '');
                if (content.length === 0) {
                    alert('实验内容不能为空，请至少填写或插入有效内容！');
                    return false;
                }
                $('#submitBtn').addClass('btn-loading').text('提交中...').prop('disabled', true);
                form.submit();

            },
            errorPlacement: function(error, element) {
                error.insertAfter(element).css('margin-top', '5px').css('font-size', '12px');
            }
        });
    });
</script>
</body>
</html>